/**
 * @author {Yuntao Zhou}
 */
 
Util.DataCell.prototype.getValue=function(){//overwrite this method to get the originalText
	return this.originalText||this.el.children('div').html();
};
var QS_News=function(callback){
//  if(typeof GB_NewsDataManager=='undefined'){
//      GB_NewsDataManager=new QS_NewsDataManager();
//  }
    this.callback=callback||{};
    this.containerId = null;
    this.container = null;
    this.id = null;
    this.intervalObj=null;
    this.intervalTime={
        'default':1200000,
        'BRIEFING_INPLAY':15000,
        'BRIEFING_TRADER':15000
    };
    var now=new Date();
    this.profile = {
        plusSymbol:false,// if exist "+" in tabmenu
        fixHeight:true,
        selectedContentID:'',
        closeable:true,
        sortable:false,
        type:'default',
        productCode:'QS',
        //currentViewID:'-1',
        showTab:true,
        tabsList:true,
        showTickerInfo:false,
        isShowContent:true,
        isSaveRange:false,
        collapseable:true,
        hasSetting:true,
        hasCustomTabList:true,
        hasDropDownMenu:true,
        settingContainer:$(document.body),
        //openedList:[-1],
        fromDate:QS_DateFormat.formatDate(new Date(now.getFullYear(),now.getMonth(),now.getDate()-30)),
        toDate:QS_DateFormat.formatDate(now),
        templates:"Generic,StockAnalystNotes,StockAnalysis,FundAnalysis,ETFAnalysis,MorningstarArticle",
        showFootbar:false,
        maxCount:100,
        needPaging:false,
        hasDatePicker:false,
        pageSize:30,
        currentPage:1,
        
        saveTitle:null,
        IMGPath:'//rtqimg.morningstar.com/img/',
        windowConfig:{},
		colWidth:{
			'Date':'20%',
			'Subject':'79%'
		},
		
		updateInterval:null
    };
	this.realDateRange={};
    this.ids=[];
    this.startAt=null;
    this.endAt=null;
    this.width=null;
    this.height=null;
    this.lock=false;
    this.el = null; 
    this.$head=null;
    this.$headLines=null;
    this.$content=null;
    this.$hideLink=null;
    this.$gridContainer=null;
    this.$pageContainer=null;
    this.$noNewsEl=null;
    this.contentScrollPN=null;
    this.head=null;
    this.gridCols=[];
    this.settingPanel=null;
    this.symbolType='single';//all,single,watchlist
    this.curW=null;
    this.ticker=null;
    this.lastTicker=null;
    this.watchlistId=null;
    this.openedList=null;   
    this.fromDate=null;
    this.toDate=null;
    this.endNewsDate=null;
    this.selectedContentID=null;
    this.pageNavigation=null;
    this.lastCallbackHeight=null;
    this.loaded=false;
    //this.minWidth=460;
    this.minHeight=260;
	this.columnSet={
		'Date':{ header: "Date",renderer:function(d){
			return QS_DateFormat.toESTDate(d);
		},customSort:function(v1,v2){//custom the sort method
			var d1=QS_DateFormat.convertToDate(v1);
			var d2=QS_DateFormat.convertToDate(v2);
			if (d1 > d2) {
				return -1;
			}else if (d1 == d2) {
				return 0;
			}else{
				return 1;
			}
		}},
		'Subject':{ header: "Subject"},
		'Source':{ header: "Source"}
	};
    this.openMoreWindow = typeof workspaceManager!='undefined'?workspaceManager.openOpenFileWin:function(){};
    this.HTML='<div class="qs-gd qs-news"><div class="hd head-container"></div><div class="bd"><div class="qs-r"><div class="qs-c first qs-news-headLines"><div class="grid-container"></div><div class="qs-no-news">No news available.</div><div class="qs-news-hide-link" idkey="hide">Hide</div></div><div class="qs-c qs-news-content"><div class="content-hd"></div><div class="data"></div></div></div></div><div class="ft"></div></div>'
};
QS_News.prototype={
    init: function(containerId,profile,id){
        var self=this;
        GB_NewsDataManager.register(id);
        this.containerId = containerId;
        this.container = $('#' + containerId);
        this.id = id;
        if(profile){
            $.extend(this.profile,profile);
        }
        var ticker,watchlistId;
        if(this.profile.symbolType){
            this.symbolType=this.profile.symbolType;
        }
        if(this.profile.ticker){
            ticker=this.profile.ticker;
        }
        if(this.profile.watchlistId){
            watchlistId=this.profile.watchlistId;
        }
        var defaultViewListMap=null;
		if(typeof this.profile.openedList=='undefined'){
            this.profile.openedList=GB_NewsDataManager.openedList[this.profile.type].slice();// get a copy
        }else{
			defaultViewListMap=GB_NewsDataManager.convertDefaultViewListToMap();
			this.profile.openedList=this._checkReturnOpenedList(defaultViewListMap,this.profile.openedList);//checked the default view validation
		}
        this.openedList=this.profile.openedList;
		
        if(typeof this.profile.currentViewID=='undefined'){
            this.profile.currentViewID=GB_NewsDataManager.currentViewID[this.profile.type];
        }else{
			if(defaultViewListMap==null){
				defaultViewListMap=GB_NewsDataManager.convertDefaultViewListToMap();
			}
			if(!this._checkCurrentViewID(defaultViewListMap,this.profile.currentViewID)){
				this.profile.currentViewID=this.openedList[0];
			}
		}
        this.currentViewID=this.profile.currentViewID;
        
        if(this.profile.fromDate){
            this.fromDate=this.profile.fromDate;
        }
        if(this.profile.toDate){
             this.toDate=this.profile.toDate;
        }
        if(this.profile.needPaging){
            this.startAt=(this.profile.currentPage-1)*this.profile.pageSize+1;
            this.endAt=this.profile.currentPage*this.profile.pageSize;
        }
        if(!this.profile.collapseable){
            this.profile.isShowContent=false;
        }
        if(this.profile.width){
            this.width=this.profile.width;
        }
        if(this.profile.height){
            this.height=this.profile.height;
        }
        if(this.profile.type!=GB_NewsDataManager.DEFAULT_TYPE){
            this.profile.hasDropDownMenu=false;
        }
        if(this.profile.curW){
            this.curW=this.profile.curW;
        }
        this.lock=this.profile.windowConfig.isCheckLock===true?true:false;
        this.el = $(this.HTML);
        this.el.appendTo(this.container);
        this.$head=this.el.find('.head-container');
        this.$headLines=this.el.find('.qs-news-headLines');
        this.$content=this.el.find('.qs-news-content');
        this.$hideLink=this.el.find('.qs-news-hide-link');
        this.$gridContainer=this.$headLines.find('.grid-container');
        this.$pageContainer=this.el.find('.ft');
        this.$noNewsEl=this.$headLines.find('.qs-no-news');
        this._createHead();
        if (this.profile.showFootbar) {
            this._createPageNavigation();
        }
        this.setGridCols(this.profile.colWidth);
        this._createGrid(0,0,this.gridCols);
        if (this.profile.fixHeight) {
            this.contentScrollPN = new Util.ScrollPanel(this.el.find('.data'));
            this.$noNewsEl.addClass('qs-no-news-fixHeighttrue');
        }else{
            this.$noNewsEl.addClass('qs-no-news-fixHeightfalse');
        }
        if (!this.profile.isShowContent) {
            this._collapseContent(this.profile.isShowContent);
        }
        this._bindEvent();
        if(this.profile.hasSetting){
            this._createSettingPanel();
        }
        GB_NewsDataManager.getViewList(this.profile.type,function(o){
            if(self.profile.hasSetting&&o&&o.length!=0&&self.profile.type==GB_NewsDataManager.DEFAULT_TYPE){
                self.settingPanel.reBindViewMenu(o);
            }
            self.openView(self.currentViewID, self.getViewName(self.currentViewID));
            if(self.symbolType!='all'){
                self.changeSymbol(self.symbolType,ticker,watchlistId);
            }
        });
    },
	_checkCurrentViewID:function(defaultViewListMap,currentViewID){
		if(currentViewID>0){
			return true;
		}else{
			if(defaultViewListMap[currentViewID]){
				return true;
			}else{
				return false;
			}
		}
	},
	_checkReturnOpenedList:function(defaultViewListMap,openedList){
		oList=[];
		if(this.profile.type==GB_NewsDataManager.DEFAULT_TYPE){
			for(var i=0,l=openedList.length;i<l;i++){
				if(openedList[i]>0){
					oList.push(openedList[i]);
					continue;
				}
				if(defaultViewListMap[openedList[i]]){
					oList.push(openedList[i]);
				}
			}
		}
		return oList;
	},
    setCurrentViewId:function(id){
		if(this.currentViewID!=id){
			this.currentViewID=id;
		}
        
    },
    getLastTicker:function(){
        return this.lastTicker;
    },
    _createPageNavigation:function(){
        var self=this;
        this.pageNavigation=new QS_News_PageNavigation(this.$pageContainer,{
            fromDate:this.fromDate,
            toDate:this.toDate,
            hasPaging:this.profile.needPaging,
            hasDatePicker:this.profile.hasDatePicker,
            navSize:this.profile.navSize
        },{
            onPageChanged:function(startAt,endAt){
                self.startAt=startAt;
                self.endAt=endAt;
                self._searchNews(true);
            },
            onDateChanged:function(s,e){
                self.changeDateRange(s,e);
            }
        });
    },
    _createHead:function(){
        var self=this;
        this.head=new QS_News_Header(this,this.$head,{
            showTab:this.profile.showTab,
            tabsList:this.profile.tabsList,
            showTickerInfo:this.profile.showTickerInfo,
            hasDropDownMenu:this.profile.hasDropDownMenu,
            plusSymbol:this.profile.plusSymbol
        },{
            onTabAfterRearrange:function(tab,ids){
                var newOpenList = [];
                //reorder openedlist
                for (var j = 0; j < ids.length; j++) {
                    for (var i in self.openedList) {
                        if (self.openedList[i] == ids[j]) {
                            newOpenList.push(self.openedList[i]);
                        }
                    }
                }
                self.openedList = newOpenList.slice();
            },
            onTabActive:function(tab){
                if(self.currentViewID!=tab.id){
                    self.openView(tab.id,tab.txt);
                }   
            },
            onTabDeActive:function(tab){
                self.stopAutoUpdate();
            },
            onTabBeforeClose:function(tab){
                self.closeView(tab.id);
            }
        });
    },
    _createSettingPanel:function(){
        var self=this;
        this.settingPanel=new NewsSettingMenu(this,$.extend({
            autoBoxID:this.containerId+"_SPAutoBox",
            settingContainer:this.profile.settingContainer,
            isSaveRange:this.profile.isSaveRange
        },this.profile.windowConfig),{
            onDateRangeChecked:function(isChecked){
                self.profile.isSaveRange=isChecked;
            },
            onTitleChanged:function(title,isAdd){
                self._changeTitle(title,isAdd);
            },
            onLockChecked:function(isLock){
                self.lock=isLock;
            },
            onHeadShowHide:function(isShow){
                if(isShow){
                    self.head.show();
                }else{
                    self.head.hide();
                }
                self.changeOutSize(self.width,self.height);
            }
        });
    },
    _getDefaultTitle:function(){
        if(this.profile.type==GB_NewsDataManager.BRF_INPLAY_TYPE){
            return 'Briefing InPlay';
        }else if(this.profile.type==GB_NewsDataManager.BRF_TRADER_TYPE){
            return 'Briefing Trader';
        }else{
            return 'News';
        }
    },
    _changeTitle:function(t,isAddSymbol,isAuto){
        if (typeof this.setTitle == 'function') {
            var title = this._getDefaultTitle(), ticker;
            if (isAuto) {
                isAddSymbol = true;
            }
            else {
                if (t != null) {
                    title = t;
                }
                else {
                    isAddSymbol = true;
                }
            }
            if (isAddSymbol) {
                if (this.symbolType == 'watchlist' && this.curW != null) {
                    ticker = this.curW;
                }
                else 
                    if (this.symbolType == 'single' && this.ticker != null) {
                        ticker = gData[gIdMap[this.ticker]].ticker;
                    }
                    else 
                        if (this.symbolType == 'all' && this.Ticker == null && this.watchlistId == null) {
                            ticker = 'All';
                        }
            }
            else {
                ticker = false;
            }
            this.profile.saveTitle = title ? title : null;
            title += ":";
            if (this.symbolType == 'all' || this.symbolType == 'watchlist') {
                this.setTitle(title, ticker, {
                    boxHide: true,
                    needReplace: false
                });
            }else {
                this.setTitle(title, ticker);
            }
        }
    },
    closeView:function(id){
        var idx=GB_NewsDataManager.inArray(id,this.openedList);
        if(idx!=-1){
            this.openedList.splice(idx,1);
        }
    },
    openView:function(id,txt,needActiveTab){
        this.currentViewID=id;
        if (GB_NewsDataManager.inArray(id,this.openedList) < 0){
            this.openedList.push(id);
        }
        if (this.profile.type == GB_NewsDataManager.DEFAULT_TYPE) {
            if (typeof txt == 'undefined') {
                txt=this.getViewName(id);
            }
            if (this.settingPanel != null) {
                this.settingPanel.updateCurrentView(txt);
            }
        }
        this.head.activeTabById(id,this.getTabList(),needActiveTab);
        //if(this._isNeedSearchDB()){
            this._searchNews(true,id);
        //}
    },
    acceptTicker:function(ticker){
        if(ticker!=this.ticker){
            if (this.settingPanel != null) {
                this.settingPanel.selectSymbolTypeRadio('single');
            }
            this.changeSymbol('single',ticker);
        }
    },
    changeSymbol:function(symbolType,t,wId){
        var self=this;
        this.symbolType=symbolType;
        if(symbolType=='all'){
            this.ticker=null;
            this.watchlistId=null;
            this.head.updateTickerInfo(symbolType);
            this._searchNews(true);
        }else if(symbolType=='single'){
            if(t==null||t==''){
                return;
            }
            if(typeof this.showLoading=='function'){
                this.showLoading();
            }
            this._checkTickers(t,function(secIds,gkeys){
                self.ticker=secIds;
                self.lastTicker=self.ticker;
                self.watchlistId=null;
                self.head.updateTickerInfo(symbolType,gkeys);
                self._searchNews(false);
            });
        }else if(symbolType=='watchlist'){
            if(wId==null||wId==''){
                return;
            }
            if(typeof this.showLoading=='function'){
                this.showLoading();
            }
            QS_watchlistDataManager.getHoldings(wId,function(holdings){ //get secids from watchlistDatamanager
                var map={},SecId,tickers=[];
                for (var i = 0, l = holdings.length; i < l; i++) {//got the performanceID
                    SecId = holdings[i].SecId;
                    if(!map[SecId]){
                        map[SecId]=true;
                        tickers.push(SecId);
                    }
                }   
                if (tickers.length == 0) {
                    Util.message('This watchlist is empty!');
                    self._changeTitle(self.profile.saveTitle, true);
                    self.fillNews(null);
                    if (typeof self.hideLoading == 'function') {
                        self.hideLoading();
                    }
                }else {
                    self._checkTickers(tickers, function(secIds, gkeys){
                        self.ticker = secIds;
                        self.watchlistId = wId;//bug#2969,2011.9.29,alex
                        self.head.updateTickerInfo(symbolType);
                        self._searchNews(false);
                    });
                }           
            });
        }
    },
    _checkTickers:function(tickers,callback){
    var self=this;
        if(this.tValidation){
            this.tValidation.checkTickers(tickers, function(list){
                if (typeof(self.hideLoading) == 'function' && typeof(list) != 'undefined' && list.length == 0) {
                    self.hideLoading();
                }
                if (!list || !list.length || list.length < 1) {
                    if(typeof self.hideLoading=='function'){
                        self.hideLoading();
                    }
                    return;
                }
                secIds = [];
                var d,len=0;
                for (var i = 0, l = list.length; i < l; i++) {
                    d = gData[list[i]];
                    if(d.secId&&d.secId.length>0){
                        secIds.push(d.secId);
                    }else if(d.performanceId&&d.performanceId.length>0){
                        secIds.push(d.performanceId);
                    }
                }
                callback(secIds.join(','),list.join(','));
                if(typeof self.callback.afterAcceptTicker=='function'){
                     self.callback.afterAcceptTicker(list[0]);
                }
            });
        }else{
            
        }
    },
    changeOutSize:function(w,h){
        var parent = this.el.parent();
        w = w>0?w:parent.width();
        h = h>0?h:parent.height();
        /*if(w<this.minWidth&&this.profile.instCode=='QUEST'){
            w=this.minWidth;
        }*/
        var size={width:w};
        if(this.profile.fixHeight){
            size.height=h;
        }
        this.width=w;
        this.height=h;
        this.el.css(size);
        if(this.profile.fixHeight){
            var headFootHeight=this.head.getHeight()+(this.pageNavigation!=null?this.pageNavigation.getHeight():0)
            if(this.profile.isShowContent){
                this._changeHeadlinesSize(null,h-headFootHeight);
                this._changeContentSize(null,h-24-headFootHeight);
            }else{
                this._changeHeadlinesSize(null,h-headFootHeight);
                this.$content.hide();
                this.$hideLink[0].innerHTML='Show';
                this.$hideLink.attr('idkey','show');
            }
        }
        var height=this.el.height();
        this.onHeightChange(height);
        if(this.head&&this.head.tabMenu&&typeof(this.head.tabMenu.reSize)=="function"){
            this.head.tabMenu.reSize();
        }
    },
    _changeHeadlinesSize:function(w,h){
        var size={};
        if(w>0){
            size.width=w;
        }
        if(h>0){
            size.height=h;
        }
        this.$gridContainer.css(size);
        this.newsGridList.resize(null,h);
    },
    _changeContentSize:function(w,h){
        if(this.profile.fixHeight){
           var size={};
            if(w>0){
                size.width=w;
            }
            if(h>0){
                size.height=h;
            }
            this.$content.find('.data').css(size);
            this.contentScrollPN.reSize(null,h);
        }
        var height=this.el.height();
        this.onHeightChange(height);
    },
    setSettingContainer:function(container){
        this.profile.settingContainer=container;
    },
    _searchNews:function(needShowLoading,id){
        var self=this;
        if(!this._isNeedSearchDB()) {
            if (typeof this.hideLoading == 'function') {
                this.hideLoading();
            }
            return;
        }
        if(QS_DateFormat.compareWithToday(this.toDate)>=0){
           this.startAutoUpdate();//start to auto update
        }
        if (typeof id == 'undefined') {
            id = this.currentViewID;
        }
        if(typeof this.showLoading=='function'&&needShowLoading){
            this.showLoading();
        }
        this._getPostParameter(id,function(postParas){
             with ({
                tempid:id
             }){
                GB_NewsDataManager.getNewsTitleList(postParas, function(o){
                    if (o == null || o == '') {
                        self.fillNews(null);
                    }
                    else {
                        var list = eval("(" + o + ")");
                        self.fillNews(list);
                    }
                    self._changeTitle(self.profile.saveTitle, true);
                    if (typeof self.hideLoading == 'function') {
                        self.hideLoading();
                    }
                });
             }
        });      
    },
    _isContainsCurrentView:function(){
        if(this.ids.length==0||this.profile.selectedContentID==''){
            return false;
        }
        if($.inArray(this.profile.selectedContentID,this.ids)>=0){
            return true;
        }else{
            return false;
        }
    },
    fillNews:function(data){
        this.el.find('.qs-no-news').hide();
        if (!data || data.length == 0 || data == null||data=='') {
            this.newsGridList.empty();
            this.$content.find('.data')[0].innerHTML='';
            this.el.find('.qs-no-news').show();
        }
        else {
            var gridData = this.createGridData(data);
            this.newsGridList.reBindData(gridData);
            if(this.profile.selectedContentID!=''&&this.profile.selectedContentID!=this.selectedContentID&&this._isContainsCurrentView()){
                this.selectedContentID=this.profile.selectedContentID;
            }else{
                this.selectedContentID=gridData[0].RId;
            }
            if(this.profile.isShowContent){
                this.newsGridList.selectRow(this.selectedContentID);
            }
        }
        this.changeOutSize(this.width,this.height);
    },
	_loadIMG:function($img,callback){
		var imgCount=0;
		var len=$img.length;
		if (len > 0) {
			$img.bind('load', function(e){
				imgCount++;
				if(imgCount==len){
					callback();
				}
			}).bind('error', function(){
				imgCount++;
				if(imgCount==len){
					callback();
				}
			});
		}else{
			callback();
		}
	},
    fillNewsContent:function(data){
        this.$content.find('.data')[0].innerHTML='';
        var self=this;
        var postData={};
        postData["pTeam"]=data.pTeam;
        postData["tpl"]=data.tpl;
        postData["rId"]=encodeURIComponent(data.RId); //fix bug#1179 - david
		postData["productCode"]=this.profile.productCode;
        var date=data.dateTime,source=data.Source,vendor=data.vendor;
        if ((typeof workspaceManager != 'undefined'&& typeof workspaceManager.openNewsDetailWin=='function')||this.profile.isShowContent) {
            GB_NewsDataManager.getNewsContent(postData, function(o){
                if (o == null || o == '') {
                    return;
                }
                var list = eval("(" + o + ")");
                var tl = (list.title == null ? "" : list.title), ct = (list.content == null ? "" : list.content);
				var a =/<html.+?<body>(.+)<\/body>.*<\/html>/.exec(ct);//fix bug that some html can not display
				if(a!=null&&a.length>1){
					ct=a[1];
				}
				var str = "<div><h2>" + tl + '</h2><div class="content-bd">' + ct + '</div>';
				if (vendor == 'Briefing') {
                    str += '<div class="rtn-content-ft"><img src="'+self.profile.IMGPath+'logo_briefing.png"/><span>Copyright @ 2012 Briefing.com, Inc. All rights reserved.</span></div>';
                }else if (vendor == 'RSSFeeds') {
                    str += '<div class="rtn-content-ft" style="padding-top:5px;height:20px;">Source: ' + source + 'RSS (' + date + ')</div>';
                }else if(vendor=='Morningstar'){
                    str += '<div class="rtn-content-ft"><img src="'+self.profile.IMGPath+ 'mstar_hd.png"/><span>Copyright 2012 Morningstar, Inc. All rights reserved.</span></div>';
                }
                str += '</div>';
                if (self.profile.isShowContent) {
                    var contentEl = self.$content.find('.data');
                    contentEl[0].innerHTML = str;
                    contentEl.find('a').attr('target', '_blank');
                    var headFootHeight=self.head.getHeight()+(self.pageNavigation!=null?self.pageNavigation.getHeight():0)
					self._loadIMG(contentEl.find('img'),function(){
						self._changeContentSize(null, self.height - 24-headFootHeight);
					});
                }
                else {
                   workspaceManager.openNewsDetailWin(tl, str);
                }
            });
        }else{
            var url=GB_NewsDataManager.dataURL.newsContent+"?productCode="+self.profile.productCode+"&pTeam="+data.pTeam+"&tpl="+data.tpl+"&rId="+encodeURIComponent(data.RId)+"&format=html&vendor="+vendor+"&source="+source+"&date="+date;
            if (typeof self.callback.customNewsClick == 'function') {
                self.callback.customNewsClick(data.Subject, url);
            }else{
                //window.open('../linkURL.jsp?u='+url,"displayWindow","toolbar=no,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no,width=800,height=600");
                window.open(url,"displayWindow","toolbar=no,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no,width=800,height=600");
            }
        }
    },
    fillNewsTitle:function(title,url){
        var self=this;
        this.$content.find('.data')[0].innerHTML='';
        if (this.profile.isShowContent) {
            this.$content.find('.data')[0].innerHTML = '<a href="javascript:void(0)"><h2 style="text-decoration:underline;" >' + title + '</h2></a>';
            this.$content.find('.data a').bind('click.news', function(e){
                self._openNewsDialog(title,url);
            });
            var headFootHeight = this.head.getHeight() + (this.pageNavigation != null ? this.pageNavigation.getHeight() : 0)
            this._changeContentSize(null, this.height - 24 - headFootHeight);
        }else{
            this._openNewsDialog(title,url);
        }
    },
    _openNewsDialog:function(title,url){
        if (typeof workspaceManager != 'undefined') {
            workspaceManager.openNewsDetailWin('News Link', "<a href='" + url + "' target='_blank' ><h2 style='text-decoration:underline;' >" + title + "</h2></a>", url);
        }else{
            //window.open('../linkURL.jsp?u='+url,"displayWindow","toolbar=no,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no,width=800,height=600");
            window.open(url,"displayWindow","toolbar=no,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no,width=800,height=600");
        }
    },
    createGridData:function(data,needAddIds){
        needAddIds=needAddIds===false?false:true;
        var result=[];
        var len=data.length,date,subject,rId,url,pTeam,tpl,sName,vendor,dTime;
        for(var i=0;i<len;i++){
            var obj=data[i];
            sName=obj.sName;
            subject=obj.title;
            rId=obj.cId||'';
            url=obj.cURL||'';
            pTeam=obj.pTeam||'';
            tpl=obj.tpl;
            vendor=obj.vendor;
            if(i==0){
                this.endNewsDate=this._getEndNewsDate(obj.dTime);
            }

            if(sName!=''){  //fixed bug#1178 - david
                var idx=subject.indexOf("["+sName+"]");
                if(idx>=0){
                    subject=subject.substring(0,idx);
                }
            }
			if(!this.profile.colWidth['Source']&&sName!=''){
				subject=subject+"&nbsp; ["+(vendor!='Acquire'?vendor+" - ":'')+sName+"]";
			}
			
            dTime=QS_DateFormat.toESTTime(obj.dTime);
            result.push({
                Date:obj.dTime,
                Subject:subject,
                RId:rId,
                Url:url,
                Source:sName,
                pTeam:pTeam,
                tpl:tpl,
                vendor:vendor,
                dateTime:dTime
            });
            if (needAddIds){
                this.ids.push(rId);
            }
        }
        return result;
    },
    _getEndNewsDate:function(d){//endNewsDate+1s,d:yyyy-mm-ddTHH:mm:ss
        var arr=d.split(':'),
            s=parseInt(arr[2])+1;
        s=s<10?('0'+s):s;
        arr[2]=s;
        return arr.join(":");
    },
    _getDateConfig:function(interval){
		var needTranserfer=true;
		var fromDate=QS_DateFormat.setTime(QS_DateFormat.convertDate(this.fromDate));
		var toDate=QS_DateFormat.setTime(QS_DateFormat.convertDate(this.toDate),'max');
		if(QS_DateFormat.compareWithToday(this.toDate)>=0){
			if(this.endNewsDate!=''&&this.endNewsDate!=null&&interval>0){
				needTranserfer=false;
				fromDate=this.endNewsDate;
			}
		}   
		return {    
			from:needTranserfer?QS_DateFormat.formatDate1(fromDate):fromDate,
			to:QS_DateFormat.formatDate1(toDate)
		}
    },
    _getPostParameter:function(id,callback,interval){
        var self=this;
        var config=this._getDateConfig(interval);
        var postData={
			productCode:this.profile.productCode,//'QS',
            lang:'en'
        };
		if(config.from&&config.to){
			postData['fromDate']=config['from'];
			postData['toDate']=config['to'];
		}
        if(this.profile.templates!=''){
            postData['templates']=this.profile.templates;
        }
        if(this.profile.needPaging){
            postData['startAt']=this.startAt;
            postData['endAt']=this.endAt;
        }else{
            postData['maxCount']=this.profile.maxCount;
        }
        if(this.profile.excludeVendor!=''){
            postData['vendor']=this.profile.excludeVendor;
            postData['vendorFlag']=-1;
        }
        if(this.symbolType!='all'){
            postData["symbols"]=this.ticker;
            postData["idType"]='SC';
        }
        if(this.profile.type==GB_NewsDataManager.DEFAULT_TYPE){
            GB_NewsDataManager.getViewSourceById(id,this.profile.type,function(o){
                $.extend(postData, self._getDefaultSourcesPara(id));
                callback(postData);
            });
        }else{
            if (id != 0) {
                postData['category'] = this._getInplayCategoryPara(id);
            }
            if(this.profile.type==GB_NewsDataManager.BRF_INPLAY_TYPE){
                postData['ntSourceCode']=3044;//breiefing inplay
            }else{
                postData['ntSourceCode']=3006;////breiefing trader
            }
            callback(postData);  
        }
    },
    _getDefaultSourcesPara:function(id){
        var sources={},nts,dcs;
        var s=GB_NewsDataManager.defaultViewSource[id];
        if(typeof s!='undefined'){
            nts=s["ntSource"],dcs=s["dcSource"];
        }
        if(nts!=null&&nts.length!=0){
            sources["ntSourceCode"]=nts.join(',');
        }
        if(dcs!=null&&dcs.length!=0){
            sources["dcSourceCode"]=dcs.join(',');
        }
        return sources;
    },
    _getInplayCategoryPara:function(id){
        for(var i=0,l=GB_NewsDataManager.briefingViewList.length;i<l;i++){
            if(GB_NewsDataManager.briefingViewList[i].vid==id){
                return GB_NewsDataManager.briefingViewList[i].val;
            }
        }
    },
    _isNeedSearchDB:function(){
        if(this.symbolType=='single'){
            if(this.ticker==null){
                return false;
            }
        }else if(this.symbolType=='watchlist'){
            if(this.watchlistId==null){
                return false;
            }
        }else if(this.symbol=='all'){
            if(this.ticker!=null||this.watchlistId!=null){
                return false;
            }
        }
        return true;
    },
    _bindEvent:function(){
        if (this.profile.collapseable) {
            var self = this;
            this.el.bind('click.News', function(e){
                var target = $(e.target);
                if (target.hasClass('qs-news-hide-link')) {
                    var key = target.attr('idkey');
                    var flag = true;
                    if (key == 'hide') {
                        flag = false;
                    }
                    self._collapseContent(flag);
                    self.changeOutSize(self.width, self.height);
                }
            });
        }else{
            this.$hideLink.hide();
        }
    },
    _collapseContent:function(flag){
        if(flag){
            this.$content[0].style.display='block';
            this.el.find('.qs-c').css('width','49.94%');
            this.$hideLink[0].innerHTML='Hide';
            this.$hideLink.attr('idkey','hide');
        }else{
            this.$content[0].style.display='none';
            this.el.find('.qs-c').eq(0).css('width','100%');
            this.$hideLink[0].innerHTML='Show';
            this.$hideLink.attr('idkey','show');
        }
        this.profile.isShowContent=flag;
        if (this.profile.isShowContent){
             this.newsGridList.selectRow(this.selectedContentID);
        }
    },
    setGridCols:function(colWidth){
		for(var col in colWidth){
			var cols=this.columnSet[col];
			cols.dataIndex=col;
			cols.width=colWidth[col];
			this.gridCols.push(cols);
		}
    },
    _createGrid:function(w,h,cols){
        var self=this;
        this.newsGridList=new Util.DataGrid(this.$gridContainer,{},{
            column:cols,
            fixSize:false,
            width:w>0?w:0,
            height:h>0?h:0,
            htmlLayer:'div',
            indexColKey:'RId',
            sortable: this.profile.sortable,
            cellResize: false,
            cellRearrange: false,
            rowInvertSelect:false,
            autoWidth:true,
            autoHeight:!this.profile.fixHeight
        },{
            onRowSelected: function(e, row){
                var url = row.data.Url,pTeam=row.data.pTeam, subject = row.data.Subject;
                self.selectedContentID = row.data.RId;
				var flag=false;
				if(pTeam=='DC'){
					if(url==''){
						flag=true;
					}
				}else{
					if(self.selectedContentID.length>0){
						flag=true;
					}
				}
				if(flag){
					self.fillNewsContent(row.data);
				}else{
					self.fillNewsTitle(subject, url);
				}
            }
        });
    },
    getTabList:function(){
        var tabList=[];
        var l=this.openedList.length;
        for(var i=0;i<l;i++){              
            tabList.push({
                id:this.openedList[i],
                txt:this.getViewName(this.openedList[i]).replace(/&/g,'&amp;'),
                closable:(!this.profile.closeable||l==1)?false:true
            });
        }
        return tabList;
    },
    getViewName:function(tabId){
        var ret=""; 
        if (this.profile.type == GB_NewsDataManager.DEFAULT_TYPE) {
            for (var i = 0, l = GB_NewsDataManager.defaultViewList.length; i < l; i++) {
                if (tabId == GB_NewsDataManager.defaultViewList[i].vid) {
                    ret = GB_NewsDataManager.defaultViewList[i].txt;
                    break;
                }
            }
        }else{
            for (var i = 0, l = GB_NewsDataManager.briefingViewList.length; i < l; i++) {
                if (tabId == GB_NewsDataManager.briefingViewList[i].vid) {
                    ret = GB_NewsDataManager.briefingViewList[i].txt;
                    break;
                }
            }
        }
        return ret;
    },
    onOpenSettingPN:function(){
        if (this.settingPanel != null) {
            if (this.profile.type != GB_NewsDataManager.DEFAULT_TYPE) {
                this.settingPanel.resizeCtList();
            }
        }
    },
    changeDateRange:function(s,e){
        var flag=false;
        if(this.fromDate!=QS_DateFormat.formatDate(s)){
            this.fromDate=QS_DateFormat.formatDate(s);
            flag=true;
        }
        if(this.toDate!=QS_DateFormat.formatDate(e)){
            this.toDate=QS_DateFormat.formatDate(e);
            flag=true;
        }
        if (flag) {
            this.stopAutoUpdate();
            if(typeof this.showLoading=='function') {
                this.showLoading(true);
            }
            this._searchNews(false,this.currentViewID);
        }
    },
    saveConfig:function(){
        var config={
            width: this.width,
            height: this.height+27,
            ticker:this.symbolType!='single'?null:this.ticker,
            isShowContent: this.profile.isShowContent,
            currentViewID: this.currentViewID,
            type:this.profile.type,
            symbolType:this.symbolType,
            watchlistId:this.symbolType!='watchlist'?null:this.watchlistId,
            curW:this.curW,
            saveTitle:this.profile.saveTitle,
            openedList:this.openedList,
            isSaveRange:this.profile.isSaveRange
        };
        if(this.profile.isSaveRange){//if user check the save,it will be saved.
            config.toDate=this.toDate;
            config.fromDate=this.fromDate;          
        }
        if(this.settingPanel!=null){
            config.windowConfig=this.settingPanel.saveConfig();
        }
        return config;
    },
    clear:function(){
        this.stopAutoUpdate();
        this.head.clear();
        if(this.pageNavigation!=null){
            this.pageNavigation.clear();
        }
        if(this.settingPanel!=null){
            this.settingPanel.clear();
        }
        GB_NewsDataManager.unregister(this.id);
        this.el.unbind(".News");
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    },
    startAutoUpdate:function(needClear){
        this.stopAutoUpdate(needClear); 
        var interval=this.profile.updateInterval || this.intervalTime[this.profile.type];
        if(interval>0){
            this.intervalObj=this._createIntervalObj(interval);
        }
    },
    stopAutoUpdate:function(needClear){ 
        needClear=needClear===false?false:true;
        if(needClear){
            this.endNewsDate='';
        }   
        if (this.intervalObj!=null) {
            clearInterval(this.intervalObj);
        }
        this.intervalObj=null;
    },
    _createIntervalObj:function(interval){  
        var self=this;
        var obj;
        var id = this.currentViewID;
        obj= setInterval(function(){
            var newsObj=self;
            if(QS_DateFormat.compareWithToday(self.toDate)<0){
                self.toDate=QS_DateFormat.formatDate(new Date());
                if (self.settingPanel != null) {
                    self.settingPanel.changeDateRangeUI(null, self.toDate);
                }
            }
            self._getPostParameter(id,function(postData){
                GB_NewsDataManager.getNewsTitleList(postData, function(o){
                    if (o == null || o == ''||!o) {
                        return;
                    }
                    var list= eval("(" + o + ")");
                    if(!list||list.length==0){
                        return;
                    }
                    self.addNews(newsObj,list);
                });
            },interval);
        }, interval);
        return obj;
    },
    addNews:function(obj,list){
        if(list.length==0){
            return;
        } 
        obj.el.find('.qs-no-news').hide(); 
        var gridData = obj.createGridData(list,false);
        var rid = gridData[0].RId;
        gridData.reverse();
        var maxSize=obj.profile.needPaging?obj.profile.pageSize:obj.profile.maxCount;
        for (var i = 0; i < gridData.length; i++) {
            obj.ids.unshift(gridData[i].RId);
            obj.newsGridList.addRow(gridData[i], gridData[i].RId, 0);
            if(obj.ids.length>maxSize){
                var lastIdx=obj.ids.length-1;
                obj.newsGridList.removeRow(obj.ids[lastIdx]);
                obj.ids.splice(lastIdx,1);
            }
        }
        if(obj.profile.isShowContent){
            obj.newsGridList.selectRow(rid);
        }
    },
    onHeightChange:function(height){
        if(height<this.minHeight){
            height=this.minHeight;
        }
        if (!this.loaded) {
            this.lastCallbackHeight = height;
            if (typeof this.callback.onLoad == 'function') {
                this.loaded = true;
                this.callback.onLoad({
                    component: 'news',
                    height: height,
                    //minWidth:this.minWidth,
                    minHeight:this.minHeight
                });
            }
        }else {
            if (this.lastCallbackHeight != height) {
                this.lastCallbackHeight = height;
                if (typeof this.callback.onHeightChange == 'function') {
                    this.callback.onHeightChange({
                        height: this.lastCallbackHeight,
                        component: 'news'
                    });
                }
            }
        }
    }
};

var QS_News_Header=function(newsObj,container,config,callback){
    this.newsObj=newsObj;
    this.el=null;
    this.container=container;
    this.tabMenu=null;
    this.ddMenu=null;
    this.$tabMenu=null;
    this.$ticekrInfo=null;
    this.activeTabId=null;
    this.tabList=null;
    this.html='<div class="qs-news-hd"><div class="tabMenu"></div><div class="tickerInfo"><h1 class="name"></h1><span class="symbol"></span><span class="rate"></span></div></div>';
    this.config={
        showTab:true,
        tabsList:true,
        showTickerInfo:false,
        rearrangeTabable:true,
        hasDropDownMenu:true,
        plusSymbol:false
    };
    this.callback={
        onTabActive:null,//function(tab){}
        onTabDeActive:null,//function(tab){}
        onTabBeforeClose:null,//function(tab){}
        onTabAfterClose:null,//function(tab){}
        onTabAfterRearrange:null//function(tab,tabIds){}
    };
    if(config){
        $.extend(this.config,config);
    }
    if(callback){
        $.extend(this.callback,callback);
    }
    this.init();
};
QS_News_Header.prototype={
    init:function(){
        this.el=$(this.html).appendTo(this.container);
        this.$tabMenu=this.el.find('.tabMenu');
        this.$ticekrInfo=this.el.find('.tickerInfo');
        this._createTabMenu();
        if(this.config.hasDropDownMenu){
            this._createDDMenu();
        }
        if(!this.config.showTickerInfo){
            this.hideTicekrInfo();
        }
        if(!this.config.showTab){
            this.hideTabMenu();
        }          
    },
    getHeight:function(){
        if(this.config.showTickerInfo&&this.config.showTab){
            return 66;
        }else if(this.config.showTickerInfo){
            return 36;
        }else if(this.config.showTab){
            return 30;
        }else{
            return 0;
        }  
    },
    getDDMenuData:function(id){
        id=id||this.activeTabId;
        var arr=[{
            type: 'separator'
        },{
            txt: 'New View...',
            val: 'cv_add'
        }];
        return [{
            txt: 'News Views',
            val: '',
            className: 'subtitle'
        },id<0?null:{
            txt: 'Edit...',
            val: 'cv_edit'
        },id<0?null:{
            txt: 'Delete',
            val: 'cv_del'
        }, {
            txt: 'Morningstar Views',
            val: 'msview',
            subMenu: GB_NewsDataManager.getDefaultViewListByGroup('msview')
        }, {
            txt: 'My Views',
            val: 'myview',
            subMenu: GB_NewsDataManager.getDefaultViewListByGroup('myview').concat(arr)
        }];
    },
    rebindDropDownMenu:function(tab){
        var self=this;
        if (tab) {
            var menuData = self.getDDMenuData();
            self.ddMenu.reBind(menuData);
            var xy = tab.menu.position();
            var winObj=self.newsObj.__winObj;
            if (winObj&&winObj.widget&&winObj.widget != self.newsObj) {//judge if it was in sr.
                var sr = winObj.widget;
                self.ddMenu.setPosition(xy.left + 10 + sr.widthCol1, xy.top +76 + sr._getBoxHeight(3));
            }
            else {
                self.ddMenu.setPosition(xy.left, xy.top + 46);
            }
            self.ddMenu.show();         
        }
    },
    _createDDMenu:function(){
        var self=this;
        var el=this.newsObj.__winObj?this.newsObj.__winObj.toolPanel:this.$tabMenu[0];
        this.ddMenu = new Util.CascadeMenu(el, {
            display: false,
            autoHide: true
        }, this.getDDMenuData(), {
            onClick: function(item){
                switch (item.data.val) { 
                    case 'cv_add':
                        GB_NewsCustomView.create(self.newsObj);
                        break; 
                    case 'cv_edit':
                        GB_NewsCustomView.edit(self.newsObj,self.activeTabId);
                        break;
                    case 'cv_del':
                        GB_NewsCustomView.remove(self.newsObj,self.activeTabId);          
                        break;
                    case 'msview':                
                    case 'myview':
                        if (item.data.vid != self.activeTabId) {
                            self.newsObj.openView(item.data.vid, item.data.txt);
                        }
                        break;
                }
                self.ddMenu.hide();
            }
        });
    },
    bindDDMenutoTab:function(tab){
        var self=this;
        tab.menu.bind('mouseover.tabnewsddl', function(){
            self.rebindDropDownMenu(tab);
        }).bind('mouseout.tabnewsddl', function(){
            self.ddMenu.hide();
        });
    },
    unBindDDMenuFromTab:function(tab){
        tab.menu.unbind('.tabnewsddl');
    },
    _createTabMenu:function(){
        var self=this;
        this.tabMenu=new Util.TabMenu(this.$tabMenu[0],[], {
            onActive: function(tab){
                if (self.config.hasDropDownMenu) {
                    self.bindDDMenutoTab(tab);
                }
                if(typeof self.callback.onTabActive=='function'){
                    self.callback.onTabActive(tab);
                }

            },
            onDeActive:function(tab){
                if(typeof self.callback.onTabDeActive=='function'){
                    self.callback.onTabDeActive(tab);
                }  
            },
            beforeClose: function(tab){
                if(typeof self.callback.onTabBeforeClose=='function'){
                    self.callback.onTabBeforeClose(tab);
                }
            },
            afterClose:function(tab){
                var tabCount = 0;
                for (var i = 0, l = self.tabMenu.tabs.length; i < l; i++) {
                    if (!self.tabMenu.tabs[i].isClose) {
                        tabCount++;
                        if(tabCount=1){
                            self.tabMenu.tabs[0].menu.addClass('noclose');
                        }
                    }
                }
                self.unBindDDMenuFromTab(tab);
                if(typeof self.callback.onTabAfterClose=='function'){
                    self.callback.onTabAfterClose(tab);
                }
                
            },
            onAddTab:function(){
                GB_NewsCustomView.create(self.newsObj);
                //console.log(workspaceManager.openWorkspaceManager);
                //workspaceManager.openWorkspaceManager();
            },
            afterRearrange: function(tab){
                var ids = self.tabMenu.getIdList();
                if(typeof self.callback.onTabAfterRearrange=='function'){
                    self.callback.onTabAfterRearrange(tab,ids);
                }
            }
        },{
            width: 100,
            marginRightWidth:26,
            plusSymbol:this.config.plusSymbol,
            autoResize: false,
            tabsList:this.config.tabsList,
            autoFixtoText: true,
            isExcuteCallbackAtInit: false,
            closeAction: 'hide',
            autoSlideToActiveTab: true,
            rearrange: this.config.rearrangeTabable
        });
    },
    activeTabById:function(id,tabList,needActiveTab){
        this.activeTabId=id;
        this.tabMenu.cfg.activeTabId = id;
        this.tabMenu.reBindData(tabList);
        if(needActiveTab) {
           this.tabMenu.getTabById(id).active(null, true);
        }
        this.tabMenu.showActiveTab(); 
        if(this.config.hasDropDownMenu){
            this.bindDDMenutoTab(this.tabMenu.currentTab);
        }
    },
    show:function(){
//      if(this.config.showTab) {
//          this.showTabMenu();
//      }
//      if(this.config.showTickerInfo){
//          this.showTicekrInfo();
//      }
        this.el.show();
    },
    hide:function(){
//      if(!this.config.showTab) {
//            this.hideTabMenu();
//        }
//        if(!this.config.showTickerInfo){
//            this.hideTicekrInfo();
//        }
        this.el.hide();
    },
    showTabMenu:function(){
        //this.config.showTab=true;
        this.$tabMenu.show();
    },
    hideTabMenu:function(){
        //this.config.showTab=false;
        this.$tabMenu.hide();
    },
    showTicekrInfo:function(){
        //this.config.showTickerInfo=true;
        this.$ticekrInfo.show();
    },
    hideTicekrInfo:function(){
        //this.config.showTickerInfo=false;
        this.$ticekrInfo.hide();
    },
    getConfig:function(){
        return this.config;
    },
    updateTickerInfo:function(type,gkey){
        if(!this.config.showTickerInfo){
            return;
        }
        var self=this;
        if (type == 'single') {
            this.showTicekrInfo();
            var gd = gData[gkey];
            this.$ticekrInfo.find('.name')[0].innerHTML = gd.Name || "";
            this.$ticekrInfo.find('.symbol')[0].innerHTML = " " + gd.clientTicker||gd.ticker;
            getStaticData([gd.secId], function(){
                if (gd["st200"] != '') {
                    var cls = "sstar" + gd["st200"]
                    self.$ticekrInfo.find('.rate').addClass(cls);
                }
            });
        }else{
            this.hideTicekrInfo();
        }
    },
    clear:function(){
        this.el.unbind(".tabnewsddl");
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    }
};
QS_News_PageNavigation=function(container,config,callback){
    this.container=container;
    this.config={
        hasPaging:false,
        hasDatePicker:false,
        pageSize:30,
        navSize:5,
        fromDate:'',
        toDate:''
    };
    this.callback={
        onDateChanged:null,//function(s,e){}
        onPageChanged:null//function(s,e){}
    };
    if(config){
        $.extend(this.config,config);
    }
    if(callback){
        $.extend(this.callback,callback);
    }
    this.el=null;
    this.$datePicker=null;
    this.$dateInput=null;
    this.$page=null;
    this.html='<div class="qs-news-pageNavigation">'+(this.config.hasDatePicker?'<span class="date-picker"><input class="qs-ui-ipt" type="text" readOnly=true/> - <input class="qs-ui-ipt" type="text" readOnly=true /> <a class="qs-ui-btn go" href="javascript:void(0)">GO</a></span>':'')+(this.config.hasPaging?'<span class="page"></span>':'')+'</div>';
    this.init();
};
QS_News_PageNavigation.prototype={
    init:function(){
        this.el=$(this.html).appendTo(this.container);
        if (this.config.hasPaging) {
             this.$page=this.el.find('.page');
            this._createPage(this.$page);
        }
        if (this.config.hasDatePicker){
            this.$dateInput=this.el.find('.date-picker input');
            this.$dateSearch=this.el.find('.date-picker .go');
            this._createDateRange(this.$dateInput);
        }
    },
    getHeight:function(){
        return this.el.height();
    },
    _createPage:function(container){
        var self=this;
        var page=new Util.PageUtil(container,{
            onClick:function(startAt,endAt){
                 if(typeof self.callback.onPageChanged=='function'){
                    self.callback.onPageChanged(startAt,endAt);
                 }
            }
        },{
            navSize:this.config.navSize,
            pageSize:this.config.pageSize
        });
    },
    _createDateRange:function(dateInput){
        var self=this;
        dateInput.eq(0).val(this.config.fromDate).data('date',QS_DateFormat.convertDate(this.config.fromDate));
        dateInput.eq(1).val(this.config.toDate).data('date',QS_DateFormat.convertDate(this.config.toDate));
        if(typeof QSCAL=='undefined'){
            var QSCAL = new Util.Calendar($('body'),{},{
                direction:'top'
            });
        }
        QSCAL.register(dateInput[0],function(date){
            var sdt=dateInput.eq(0).data('date');
            var edt=dateInput.eq(1).data('date');
            if (date.getTime() > edt.getTime()) {
                dateInput.eq(0).data('date',edt);
                dateInput.eq(1).data('date',date).val(QS_DateFormat.formatDate(date));
            }else {
                dateInput.eq(0).data('date',date);
            }
            dateInput.eq(0).val(QS_DateFormat.formatDate(dateInput.eq(0).data('date')));         
        });
        QSCAL.register(dateInput[1],function(date){
            var sdt=dateInput.eq(0).data('date');
            var edt=dateInput.eq(1).data('date');
            if(date.getTime()<sdt.getTime()){
                dateInput.eq(1).data('date',sdt);
                dateInput.eq(0).data('date',date).val(QS_DateFormat.formatDate(date));
            }
            else{
                dateInput.eq(1).data('date',date);
            }
            dateInput.eq(1).val(QS_DateFormat.formatDate(dateInput.eq(1).data('date')));  
        });
        dateInput.focus(function(e){
            if ($.browser.msie) {       // fixed the issue that hit backspace key will back the web page.
                document.body.focus();
            }
            QSCAL.show(e.target,$(e.target).data('date'));      
        });
        this.$dateSearch.bind('click.newNav',function(e){
            var sdt=dateInput.eq(0).data('date');
            var edt=dateInput.eq(1).data('date');
            if(typeof self.callback.onDateChanged=='function'){
                self.callback.onDateChanged(sdt,edt);
            }  
        });
    },
    clear:function(){
        QSCAL.unregister(this.$dateInput[0]);
        QSCAL.unregister(this.$dateInput[1]);
        this.el.unbind(".newNav");
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    }
};
